var qtpz = {
    setBtnStatus: function () {
        var row = $('#grid_qtpz').datagrid('getSelected');
        if (row && row.id) {
            $("#btn_qtpz_detail").show();
            $("#btn_qtpz_copy").show();
            //已保存
            if (row.zt == 1) {
                //未导入
                if (row.czzt == 'wdr') {
                    $("#btn_qtpz_mod").show();
                    $("#btn_qtpz_del").show();
                    $("#btn_qtpz_import").show();
                    $("#btn_qtpz_revoke").hide();
                    $("#btn_qtpz_rest").hide();
                }
                if (row.czzt == 'drcg') {
                    $("#btn_qtpz_mod").hide();
                    $("#btn_qtpz_del").hide();
                    $("#btn_qtpz_import").hide();
                    $("#btn_qtpz_revoke").show();
                    $("#btn_qtpz_rest").hide();
                }
                if (row.czzt == 'drsb') {
                    $("#btn_qtpz_mod").hide();
                    $("#btn_qtpz_del").hide();
                    $("#btn_qtpz_import").hide();
                    $("#btn_qtpz_revoke").hide();
                    $("#btn_qtpz_rest").show();
                }
                if (row.czzt == 'sccg') {
                    $("#btn_qtpz_mod").show();
                    $("#btn_qtpz_del").show();
                    $("#btn_qtpz_import").show();
                    $("#btn_qtpz_revoke").hide();
                    $("#btn_qtpz_rest").hide();
                }
                if (row.czzt == 'scsb') {
                    $("#btn_qtpz_mod").hide();
                    $("#btn_qtpz_del").hide();
                    $("#btn_qtpz_import").hide();
                    $("#btn_qtpz_revoke").hide();
                    $("#btn_qtpz_rest").show();
                }
            } else {
                $("#btn_qtpz_mod").show();
                $("#btn_qtpz_del").show();
                $("#btn_qtpz_import").hide();
                $("#btn_qtpz_revoke").hide();
                $("#btn_qtpz_rest").hide();
            }
        } else {
            $("#btn_qtpz_mod").hide();
            $("#btn_qtpz_del").hide();
            $("#btn_qtpz_copy").hide();
            $("#btn_qtpz_import").hide();
            $("#btn_qtpz_revoke").hide();
            $("#btn_qtpz_rest").hide();
        }
    }
}
$(function () {
    //表格初始加载
    var grid = $('#grid_qtpz').datagrid({
        url: $.webPath() + "/cwgl/qtpz/qtpzList",
        toolbar: "#toolbar_qtpz",
        fitColumns: true,
        singleSelect: true,
        pagination: true,
        fit: true,
        rownumbers: true,
        pageNumber: 1,
        striped: true,
        queryParams: {
            status: $("#toolbar_qtpz [name='status']").val(),
            saveStatus: $("#toolbar_qtpz [name='saveStatus']").val(),
            word: $("#toolbar_qtpz [name='word']").val()
        },
        columns: [
            [
                {field: 'id', title: '单据号', width: 8, align: 'center'},
                {field: 'zh', title: '字号', width: 8, align: 'center'},
                {field: 'nbgsqc', title: '公司', width: 25, align: 'center'},
                {field: 'zy', title: '摘要', width: 25, align: 'center'},
                {field: 'xm', title: '制单人', width: 8, align: 'center'},
                //{field: 'dateCreated', title: '制单日期', width: 10, align: 'center'},
                {field: 'zdrq', title: '制单日期', width: 10, align: 'center'},
                {field: 'voucherNum', title: '凭证号', width: 10, align: 'center'},
                {field: 'bz', title: '备注', width: 10, align: 'center'},
                {field: 'zt', title: '保存状态', align: 'center', width: 7, formatter: function (value, row, index) {
                    if (value == 0)
                        return "暂存";
                    if (value == 1)
                        return "已保存";
                    return "";
                }},
                {field: 'czzt', title: '状态', align: 'center', width: 8, formatter: function (value, row, index) {
                    if (value == 'wdr')
                        return "未导入";
                    if (value == 'drcg')
                        return "导入成功";
                    if (value == 'drsb')
                        return "导入失败";
                    if (value == 'sccg')
                        return "删除成功";
                    if (value == 'scsb')
                        return "删除失败";
                    return "";
                }}
            ]
        ],
        onLoadSuccess: function () {
            qtpz.setBtnStatus();
            $(".datagrid-htable .datagrid-cell").css('text-align', 'center');
        },
        onClickRow: function () {
            qtpz.setBtnStatus();
        },
        onDblClickRow: function (rowIndex, rowData) {
            if (rowData.czzt == 'wdr' || rowData.czzt == 'sccg')
                qtpzModify();
        }
    });
    //**********按钮触发事件**********
    //查看按钮
    $("#btn_qtpz_detail").click(function () {
        qtpzDetail();
    });
    //新增按钮
    $("#btn_qtpz_add").click(function () {
        qtpzAdd();
    });
    //修改按钮
    $("#btn_qtpz_mod").click(function () {
        qtpzModify();
    });
    //删除按钮
    $("#btn_qtpz_del").click(function () {
        qtpzDelete();
    });
    //复制按钮
    $("#btn_qtpz_copy").click(function () {
        qtpzCopy();
    });
    //导入按钮
    $("#btn_qtpz_import").click(function () {
        qtpzImport();
    });
    //撤销凭证按钮
    $("#btn_qtpz_revoke").click(function () {
        qtpzRevoke();
    });
    //重置凭证按钮
    $("#btn_qtpz_rest").click(function () {
        qtpzRest();
    });
    //重置凭证按钮
    $("#btn_qtpz_sync").click(function () {
        qtpzSync();
    });
    //查询按钮
    $("#btn_qtpz_search").click(function () {
        reloadQtpzDataGrid();
    });

    function reloadQtpzDataGrid() {
        $('#grid_qtpz').datagrid('reload',
            {
                status: $("#toolbar_qtpz [name='status']").val(),
                saveStatus: $("#toolbar_qtpz [name='saveStatus']").val(),
                startDate: $("#toolbar_qtpz [name='startDate']").val(),
                endDate: $("#toolbar_qtpz [name='endDate']").val(),
                companyId: $("#toolbar_qtpz [name='companyId']").val(),
                no: $("#toolbar_qtpz [name='no']").val(),
                voucherNo: $("#toolbar_qtpz [name='voucherNo']").val(),
                word: $("#toolbar_qtpz [name='word']").val(),
                createUser: $("#toolbar_qtpz [name='createUser']").val()
            }
        );
    }

    function qtpzDetail() {
        var record = $("#grid_qtpz").datagrid("getSelected");
        if (record == null) {
            $.messager.alert("提示", "请选择要查看的凭证!", "warning");
            return;
        }
        var href = $.webPath() + "/cwgl/qtpz/qtpz_import_content?id=" + record.id;
        qtpz_showDetailDialog("详细", "icon-tip", href);
    }

    function qtpzAdd() {
        var href = $.webPath() + "/cwgl/qtpz/qtpz_content?operation=add";
        var actionUrl = $.webPath() + "/cwgl/qtpz/save";
        qtpz_show3ButtonDialog('新增', "icon-add", href, actionUrl);
    }

    //修改
    function qtpzModify() {
        var record = $("#grid_qtpz").datagrid("getSelected");
        if (record == null) {
            $.messager.alert("提示", "请选择要更新的记录!", "warning");
            return;
        }
        var href = $.webPath() + "/cwgl/qtpz/qtpz_content?id=" + record.id + "&operation=modify";
        var actionUrl = $.webPath() + "/cwgl/qtpz/update";
        if (record.zt == 0)
            qtpz_show3ButtonDialog("修改", "icon-edit", href, actionUrl);
        else
            qtpz_show2ButtonDialog("修改", "icon-edit", href, actionUrl);
    }

    //删除
    function qtpzDelete() {
        var row = $('#grid_qtpz').datagrid('getSelected');
        if (row) {
            $.messager.confirm('提示', '是否删除该凭证？', function (r) {
                if (r) {
                    $.ajax({
                        url: $.webPath() + "/cwgl/qtpz/delete",
                        dataType: 'json',
                        type: 'POST',
                        data: {id: row.id},
                        beforeSend: function () {
                            $("#layout_qtpz").mask();
                        },
                        success: function (data) {
                            $("#layout_qtpz").mask("hide");
                            if (data.statusCode == 200) {
                                reloadQtpzDataGrid();
                                $.messager.show({
                                    title: '提示',
                                    msg: data.message,
                                    timeout: 3000,
                                    showType: 'slide'
                                });
                            } else {
                                $.messager.alert("提示", data.message, "error");
                            }
                        }
                    });
                }
            });
        } else {
            $.messager.alert("提示", "请选择要删除的凭证！", "warning");
        }
    }

    //复制
    function qtpzCopy() {
        var record = $("#grid_qtpz").datagrid("getSelected");
        if (record == null) {
            $.messager.alert("提示", "请选择要复制的凭证!", "warning");
            return;
        }
        var href = $.webPath() + "/cwgl/qtpz/qtpz_content?id=" + record.id + "&operation=copy";
        var actionUrl = $.webPath() + "/cwgl/qtpz/copy";
        qtpz_show3ButtonDialog("复制", "icon-copy", href, actionUrl);
    }

    //导入
    function qtpzImport() {
        var record = $("#grid_qtpz").datagrid("getSelected");
        if (record == null) {
            $.messager.alert("提示", "请选择要导入的凭证!", "warning");
            return;
        }
        //var href = $.webPath() + "/cwgl/qtpz/qtpz_import_content?id=" + record.id;
        var actionUrl = $.webPath() + "/cwgl/qtpz/generate_voucher";
        //qtpz_showUneditedDialog("导入", "icon-in", href, actionUrl);
        operateVoucher(record.id, actionUrl, "是否确认导入该凭证？");
    }

    //撤销
    function qtpzRevoke() {
        var record = $("#grid_qtpz").datagrid("getSelected");
        if (record == null) {
            $.messager.alert("提示", "请选择要撤销的凭证!", "warning");
            return;
        }
        //var href = $.webPath() + "/cwgl/qtpz/qtpz_import_content?id=" + record.id;
        var actionUrl = $.webPath() + "/cwgl/qtpz/revoke_voucher";
        //qtpz_showUneditedDialog("撤销", "icon-in", href, actionUrl);
        operateVoucher(record.id, actionUrl, "是否确认撤销该凭证？");
    }

    //重置
    function qtpzRest() {
        var record = $("#grid_qtpz").datagrid("getSelected");
        if (record == null) {
            $.messager.alert("提示", "请选择要重置的凭证!", "warning");
            return;
        }
        //var href = $.webPath() + "/cwgl/qtpz/qtpz_import_content?id=" + record.id;
        var actionUrl = $.webPath() + "/cwgl/qtpz/rest_voucher";
        //qtpz_showUneditedDialog("重置", "icon-reload", href, actionUrl);
        operateVoucher(record.id, actionUrl, "是否确认重置该凭证？");
    }

    //同步
    function qtpzSync() {
        var record = $("#grid_qtpz").datagrid("getSelected");
        if (record == null) {
            $.messager.alert("提示", "请选择要重置的凭证!", "warning");
            return;
        }
        //var href = $.webPath() + "/cwgl/qtpz/qtpz_import_content?id=" + record.id;
        var actionUrl = $.webPath() + "/cwgl/qtpz/sync_voucher_num";
        //qtpz_showUneditedDialog("重置", "icon-reload", href, actionUrl);
        operateVoucher(record.id, actionUrl, "是否确认同步该凭证凭证号？");
    }

    //弹出新增或修改的窗口
    function qtpz_show3ButtonDialog(title, iconCls, href, actionUrl) {
        var win = $.window({
            title: title,
            iconCls: iconCls,
            width: 850,
            height: 470,
            maximizable: true,
            cache: false,
            url: href,
            modal: true,
            onMaximize: function () {
                $(this).find("#qtpzcontent_edatagrid").edatagrid("resize");
            },
            onRestore: function () {
                $(this).find("#qtpzcontent_edatagrid").edatagrid("resize");
            },
            buttons: [
                {
                    text: '保存',
                    handler: function () {
                        var v = $(win).find('#form_qtpz').form('validate');
                        if (!v)
                            return;
                        $(win).mask();
                        $.messager.confirm('提示', '是否确定保存该凭证？', function (r) {
                            if (r) {
                                $(win).find('#form_qtpz').form('submit', {
                                    url: actionUrl,
                                    onSubmit: function (param) {
                                        var isValid = submitHandle(win, this, param, 1);
                                        return isValid;
                                    },
                                    success: function (data) {
                                        successHandle(win, data);
                                    }
                                });
                            } else {
                                $(win).mask('hide');
                            }
                        });
                    }
                },
                {
                    text: '暂存',
                    handler: function () {
                        var v = $(win).find('#form_qtpz').form('validate');
                        if (!v)
                            return;
                        $(win).mask();
                        $(win).find('#form_qtpz').form('submit', {
                            url: actionUrl,
                            onSubmit: function (param) {
                                return submitHandle(win, this, param, 0);
                            },
                            success: function (data) {
                                successHandle(win, data);
                            }
                        });
                    }
                }
            ]
        });
    }

    //弹出新增或修改的窗口
    function qtpz_show2ButtonDialog(title, iconCls, href, actionUrl) {
        var win = $.window({
            title: title,
            iconCls: iconCls,
            width: 850,
            height: 470,
            maximizable: true,
            cache: false,
            url: href,
            modal: true,
            onMaximize: function () {
                $(this).find("#qtpzcontent_edatagrid").edatagrid("resize");
            },
            onRestore: function () {
                $(this).find("#qtpzcontent_edatagrid").edatagrid("resize");
            },
            buttons: [
                {
                    text: '保存',
                    handler: function () {
                        var v = $(win).find('#form_qtpz').form('validate');
                        if (!v)
                            return;
                        $(win).mask();
                        $.messager.confirm('提示', '是否确定保存该凭证？', function (r) {
                            if (r) {
                                $(win).find('#form_qtpz').form('submit', {
                                    url: actionUrl,
                                    onSubmit: function (param) {
                                        var isValid = submitHandle(win, this, param, 1);
                                        return isValid;
                                    },
                                    success: function (data) {
                                        successHandle(win, data);
                                    }
                                });
                            } else {
                                $(win).mask('hide');
                            }
                        });
                    }
                }
            ]
        });
    }

    //弹出凭证查看窗口
    function qtpz_showDetailDialog(title, iconCls, href) {
        var win = $.window({
            title: title,
            iconCls: iconCls,
            width: 850,
            height: 470,
            maximizable: true,
            cache: false,
            url: href,
            modal: true,
            onMaximize: function () {
                $(this).find("#qtpz_import_content_datagrid").edatagrid("resize");
            },
            onRestore: function () {
                $(this).find("#qtpz_import_content_datagrid").edatagrid("resize");
            }
        });
    }

    //弹出凭证窗口
    function qtpz_showUneditedDialog(title, iconCls, href, actionUrl) {
        var win = $.window({
            title: title,
            iconCls: iconCls,
            width: 850,
            height: 470,
            maximizable: true,
            cache: false,
            url: href,
            modal: true,
            onMaximize: function () {
                $(this).find("#qtpz_import_content_datagrid").edatagrid("resize");
            },
            onRestore: function () {
                $(this).find("#qtpz_import_content_datagrid").edatagrid("resize");
            },
            buttons: [
                {
                    text: '确定',
                    handler: function () {
                        $(win).mask();
                        $.messager.confirm('提示', '是否确定操作该凭证？', function (r) {
                            if (r) {
                                $.ajax({
                                    type: "POST",
                                    url: actionUrl,
                                    dataType: "json",
                                    data: {id: $(win).find("#qtpz_import_content_toolbar [name='qtpz.id']").val()},
                                    success: function (msg) {
                                        $(win).mask("hide");
                                        $(win).dialog('close');
                                        reloadQtpzDataGrid();
                                        if (msg.responseflag == 0)
                                            $.messager.alert("提示", msg.responsemessage, "error");
                                        else {
                                            $.messager.show({
                                                title: '提示',
                                                msg: msg.responsemessage,
                                                timeout: 3000,
                                                showType: 'slide'
                                            });
                                        }
                                    }
                                });
                            } else {
                                $(win).mask('hide');
                            }
                        });
                    }
                }
            ]
        });
    }

    function operateVoucher(voucherId, actionUrl, message) {
        $.messager.confirm('提示', message, function (r) {
            if (r) {
                $.mask();
                $.ajax({
                    type: "POST",
                    url: actionUrl,
                    dataType: "json",
                    data: {id: voucherId},
                    success: function (msg) {
                        $.mask.hide();
                        reloadQtpzDataGrid();
                        if (msg.responseflag == 0)
                            $.messager.alert("提示", msg.responsemessage, "error");
                        else {
                            $.messager.show({
                                title: '提示',
                                msg: msg.responsemessage,
                                timeout: 3000,
                                showType: 'slide'
                            });
                        }
                    }
                });
            }
        });
    }

    function submitHandle(win, form, param, zt) {
        //结束编辑列的编辑状态
        $(win).find('#qtpzcontent_edatagrid').edatagrid("saveRow");
        var r = $(win).find('#qtpzcontent_edatagrid').edatagrid("getSelected");
        var index = $(win).find('#qtpzcontent_edatagrid').edatagrid("getRowIndex", r);
        $(win).find('#qtpzcontent_edatagrid').edatagrid("endEdit", index);
        var data = $(win).find('#qtpzcontent_edatagrid').edatagrid("getData");
        var footer = $(win).find('#qtpzcontent_edatagrid').datagrid('getFooterRows');
        var jfhj = isNaN(parseFloat(footer[0]["jfje"])) ? 0 : parseFloat(footer[0]["jfje"]);
        var dfhj = isNaN(parseFloat(footer[0]["dfje"])) ? 0 : parseFloat(footer[0]["dfje"]);
        //验证主信息表单
        var isValid = $(form).form('validate');
        if (!isValid) {
            $(win).mask('hide');
            return false;
        }
        if (zt == 1) {
            //验证是否有分录
            if (data.rows.length < 2) {
                $(win).mask('hide');
                $.messager.alert("提示", "请填写凭证分录!", "waring");
                return false;
            }

            for (var i = 0; i < data.rows.length; i++) {
                //验证摘要
                if ($.trim(data.rows[i]["zy"]).length == 0) {
                    $(win).mask('hide');
                    $(win).find('#qtpzcontent_edatagrid').edatagrid("selectRow", i);
                    $.messager.alert("提示", "第" + (i + 1) + "条分录摘要不能为空!", "waring");
                    return false;
                }
                //验证科目
                if ($.trim(data.rows[i]["kmmc"]).length == 0) {
                    $(win).mask('hide');
                    $(win).find('#qtpzcontent_edatagrid').edatagrid("selectRow", i);
                    $.messager.alert("提示", "第" + (i + 1) + "条分录科目不能为空!", "waring");
                    return false;
                }
                //验证辅助核算
                var items = [];
                if ($.trim(data.rows[i]["fzhs"]) != '')
                    items = $.trim(data.rows[i]["fzhs"]).split("；");
                var itemsArray = new Array();
                for (var j = 0; j < items.length; j++) {
                    if (data.rows[i]["fzhsList[" + j + "].code"] == "" || data.rows[i]["fzhsList[" + j + "].code"] == undefined)
                        itemsArray.push(items[j]);
                }
                if (itemsArray.length != 0) {
                    $(win).mask('hide');
                    $(win).find('#qtpzcontent_edatagrid').edatagrid("selectRow", i);
                    $.messager.alert("提示", "第" + (i + 1) + "条分录辅助核算【" + itemsArray.join(",") + "】不能为空!", "waring");
                    return false;
                }
            }
            //验证借贷金额
            if (jfhj != dfhj) {
                $(win).mask('hide');
                $.messager.alert("提示", "录入借贷不平!", "waring");
                return false;
            }
        }

        var arrayPrefix = "qtpz.qtpzflList";
        var paramString = "{"
        for (var i = 0; i < data.rows.length; i++) {
            var objectString = $.toJSONStringPrefix(data.rows[i], arrayPrefix + "[" + i + "].");
            paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
        }
        paramString = paramString + "\"qtpz.zt\":" + zt + ",\"qtpz.jfhj\":" + jfhj + ",\"qtpz.dfhj\":" + dfhj + "}";
        $.extend(param, $.parseJSON(paramString));
        return isValid;
    }

    function successHandle(win, data) {
        $(win).mask('hide');
        var json = $.parseJSON(data);
        if (json.statusCode == 200) {
            $(win).dialog('close');
            reloadQtpzDataGrid();
            $.messager.show({
                title: '提示',
                msg: json.message,
                timeout: 3000,
                showType: 'slide'
            });
        } else {
            $.messager.alert('提示', json.message, 'error');
        }
    }

});
